package com.moba.service;

import com.moba.domain.*;
import com.moba.emums.BaseDataType;
import com.moba.emums.BiChuOrRu;
import com.moba.emums.BiGetType;
import com.moba.emums.BiType;
import com.moba.emums.orderInfo.OrderState;
import com.moba.mapper.OrderInfoMapper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author li, bai, qiang
 * @version 2019-03-04 14:10
 * @date 2019-03-04 14:10
 */
@Service
@Transactional
public class OrderInfoService {

  @Resource private OrderInfoMapper orderInfoMapper;

  @Autowired UserInfoService userInfoService;

  @Autowired BaseDataService baseDataService;

  @Autowired SysSettingService sysSettingService;

  @Autowired UserBiRecordService userBiRecordService;
  @Autowired OrderInfoService orderInfoService;

  @Resource UserRelationParService userRelationParService;

  protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(OrderInfoService.class);

  public OrderInfo getEntity(OrderInfo t) {

    OrderInfo orderInfo = this.orderInfoMapper.selectEntity(t);

    return orderInfo;
  }

  public Integer getEntityCount(OrderInfo t) {
    return this.orderInfoMapper.selectEntityCount(t);
  }

  public BigDecimal getEntitySumMoneyBi(OrderInfo t) {
    return this.orderInfoMapper.selectEntitySumMoneyBi(t);
  }

  public BigDecimal getEntitySumOrderMoney(OrderInfo t) {
    return this.orderInfoMapper.selectEntitySumOrderMoney(t);
  }

  public List<OrderInfo> getEntityList(OrderInfo t) {
    return this.orderInfoMapper.selectEntityList(t);
  }

  public List<OrderInfo> getDistinctTempList(OrderInfo t) {
    return this.orderInfoMapper.selectEntityDistinctTempList(t);
  }

  public Integer createEntity(OrderInfo t) {
    int id = this.orderInfoMapper.insertEntity(t);

    if (null != t.getMap().get("add_leiji_money_user")) {

      // 增加用户排单数
      Integer maxOderCount = Integer.valueOf(t.getMap().get("maxOderCount").toString());

      UserInfo userInfo = new UserInfo();
      userInfo.setId(t.getAddUserId());
      userInfo = userInfoService.getEntity(userInfo);

      OrderInfo updateOrder = new OrderInfo();
      updateOrder.setId(t.getId());

      //      if (userInfo.getOrderCount().intValue() == 0 || userInfo.getOrderCount().intValue() ==
      // 5) {
      //        logger.info("====这是一个新的轮回====");
      //        updateOrder.setTemp(t.getTradeIndex());
      //      } else {
      //        OrderInfo q = new OrderInfo();
      //        q.setAddUserId(t.getAddUserId());
      //        q.getMap().put("order_by_id_asc", "true");
      //        List<OrderInfo> qlist = orderInfoService.getEntityList(q);
      //        logger.info("====同一轮回====" + qlist.get(qlist.size() - 2).getTemp());
      //        updateOrder.setTemp(qlist.get(qlist.size() - 2).getTemp());
      //        //        }
      //      }

      if (null != updateOrder.getId()) {
        updateOrder.setTempIndex(maxOderCount - userInfo.getOrderCount());
        if (updateOrder.getTempIndex() == 0) {
          updateOrder.setTempIndex(maxOderCount);
        }

        orderInfoService.updateEntity(updateOrder);
      }

      UserInfo updateUser = new UserInfo();
      updateUser.setId(userInfo.getId());

      if (userInfo.getOrderCount() + 1 > maxOderCount) {
        updateUser.setOrderCount(1);
      } else {
        updateUser.getMap().put("addUserOrderCount", 1);
      }

      userInfoService.updateEntity(updateUser);

      if (null != t.getMap().get("subOrderMoneySum")) {
        updateUser = new UserInfo();
        updateUser.setId(userInfo.getId());
        updateUser.getMap().put("subOrderMoneySum", t.getMap().get("subOrderMoneySum").toString());
        userInfoService.updateEntity(updateUser);

        logger.info("====开始插入减少矿源记录===");
        // 减少矿源
        userInfoService.updateBi(
            t.getAddUserId(),
            null,
            BiGetType.BI_GET_TYPE_90.getIndex(),
            BiType.BI_TYPE_400.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_X1.getIndex(),
            new BigDecimal(t.getMap().get("subOrderMoneySum").toString()),
            t.getId());
      }
    }

    logger.info("====开始插入GHMI操作记录===");
    // 创建记录
    UserBiRecord insertUserBiRecord = new UserBiRecord();
    insertUserBiRecord.setBiChuOrRu(-1);
    insertUserBiRecord.setOrderId(t.getId());
    insertUserBiRecord.setLinkId(t.getId());
    insertUserBiRecord.setBiType(BiType.BI_TYPE_100.getIndex());
    insertUserBiRecord.setBiGetType(BiGetType.BI_GET_TYPE_70.getIndex());
    insertUserBiRecord.setBiGetMemo(BiGetType.BI_GET_TYPE_70.getName());
    insertUserBiRecord.setBiNo(t.getMoneyBi());
    insertUserBiRecord.setBiNoBefore(new BigDecimal(t.getMap().get("ghmi_has").toString()));
    insertUserBiRecord.setBiNoAfter(insertUserBiRecord.getBiNoBefore().subtract(t.getMoneyBi()));
    insertUserBiRecord.setAddUserId(t.getAddUserId());
    insertUserBiRecord.setBiState(0);
    insertUserBiRecord.setIsDel(0);
    insertUserBiRecord.setAddDate(new Date());
    insertUserBiRecord.setAddUname(t.getAddUserName());
    userBiRecordService.createEntity(insertUserBiRecord);

    return t.getId();
  }

  public int updateEntity(OrderInfo t) {
    int id = this.orderInfoMapper.updateEntity(t);

    if (null != t.getMap().get("send_gusd")) {
      BigDecimal send_gusd = new BigDecimal(t.getMap().get("send_gusd").toString()); // 分红
      // 发放订单分红
      logger.info("====发放订单分红====");
      userInfoService.updateBi(
          t.getAddUserId(),
          null,
          BiGetType.BI_GET_TYPE_1.getIndex(),
          BiType.BI_TYPE_500.getIndex(),
          BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
          send_gusd,
          t.getId());

      OrderInfo orderInfo = new OrderInfo();
      orderInfo.setId(t.getId());
      orderInfo = orderInfoService.getEntity(orderInfo);

      UserInfo userInfo = new UserInfo();
      userInfo.setId(orderInfo.getAddUserId());
      userInfo.setIsDel(0);
      userInfo = userInfoService.getEntity(userInfo);

      logger.info("===========开始计算订单分红====");
      logger.info("===========开始计算订单分红====");
      logger.info("===========开始计算订单分红====");
      logger.info("===========订单收益金额：" + orderInfo.getProfitMoney());

      // 订单添加人的所有上级
      UserRelationPar userRelationPar = new UserRelationPar();
      userRelationPar.setUserId(userInfo.getId());
      List<UserRelationPar> userRelationParList =
          userRelationParService.getEntityList(userRelationPar);
      userRelationParList:
      for (UserRelationPar b : userRelationParList) {

        BigDecimal sendMoney = orderInfo.getProfitMoney();

        UserInfo parUser = new UserInfo();
        parUser.setId(b.getUserParId());
        parUser.setIsDel(0);
        parUser = userInfoService.getEntity(parUser);
        if (null == parUser) {
          logger.info("===用户不存在:" + parUser.getUserName() + "，跳出===");
          continue userRelationParList;
        }

        SimpleDateFormat sdFormatYmd = new SimpleDateFormat("yyyy-MM-dd");

        // 判断当前用户是否能够领取奖励
        // 当前订单的下单时间，同一天，上级用户是否有下单
        OrderInfo parOrder = new OrderInfo();
        parOrder.setAddUserId(parUser.getId());
        parOrder.getMap().put("st_add_date", sdFormatYmd.format(new Date()));
        parOrder.getMap().put("en_add_date", sdFormatYmd.format(new Date()));
        List<OrderInfo> parOrderList = orderInfoService.getEntityList(parOrder);
        //        if (null == parOrderList || parOrderList.size() == 0) {
        // 无效用户 跳出
        //          logger.info("===无效用户:" + parUser.getUserName() + "，跳出===");
        //          continue userRelationParList;
        //        }

        //        parOrderList = orderInfoService.getEntityList(parOrder);
        if (null == parOrderList || parOrderList.size() == 0) {
          // 获取所有订单中最高的那个订单
          logger.info("====上级用户同一天没有下订单。开始找最高的锁定订单=====");

          parOrder = new OrderInfo();
          parOrder.setAddUserId(parUser.getId());
          parOrder.setOrderState(OrderState.ORDER_STATE_10.getIndex());
          parOrderList = orderInfoService.getEntityList(parOrder);
          if (null == parOrderList || parOrderList.size() == 0) {
            continue userRelationParList;
          }

          OrderInfo maxOrder = new OrderInfo();
          BigDecimal 当前轮回中最大金额 = new BigDecimal(0);
          for (int i = 0; i < parOrderList.size(); i++) {
            OrderInfo a = parOrderList.get(i);
            if (当前轮回中最大金额.compareTo(a.getOrderMoney()) < 0) {
              当前轮回中最大金额 = a.getOrderMoney();
              maxOrder = a;
            }
          }
          logger.info("maxOrder:" + maxOrder.getTradeIndex() + ",金额：" + maxOrder.getOrderMoney());
          parOrder = maxOrder;
        } else {
          parOrder = parOrderList.get(0);
        }

        UserInfo ymidUser = new UserInfo();
        ymidUser.setYmid(parUser.getMobile());
        ymidUser.setIsDel(0);
        int 直推人数 = userInfoService.getEntityCount(ymidUser);

        // 上级用户的直推人数
        //        UserRelationPar d = new UserRelationPar();
        //        d.setUserParId(parUser.getId());
        //        d.setUserParLevle(1);
        //        int 直推人数 = userRelationParService.getEntityCount(d);
        logger.info("上级直推人数:" + 直推人数 + ",当前层数" + b.getUserParLevle().intValue());
        if (直推人数 < b.getUserParLevle().intValue()) {
          logger.info("===直推人数不足，跳出===");
          continue userRelationParList;
        }

        // 发奖励
        BigDecimal 默认奖励比例 = new BigDecimal(0.01);
        BaseData baseData = new BaseData();
        baseData.setType(BaseDataType.BaseDataType_60.getIndex());
        baseData.setTypeValue(b.getUserParLevle().intValue());
        baseData.setIsDel(0);
        baseData = baseDataService.getEntity(baseData);
        if (null == baseData) {
          // 那就查找范围
          baseData = new BaseData();
          baseData.setType(BaseDataType.BaseDataType_60.getIndex());
          baseData.setIsDel(0);
          baseData.getMap().put("type_value_le", 直推人数);
          logger.info("====当前" + 直推人数 + "层");
          List<BaseData> baseDataList = baseDataService.getEntityList(baseData);
          if (null == baseDataList || baseDataList.size() == 0) {
            continue;
          } else {
            baseData = baseDataList.get(baseDataList.size() - 1);
          }
        }

        默认奖励比例 = baseData.getValue2().divide(new BigDecimal(100));
        logger.info("===奖励比例:" + 默认奖励比例);

        BigDecimal 分红金额 = sendMoney.multiply(默认奖励比例);
        logger.info(
            "===上级用户订单金额:" + parOrder.getOrderMoney() + "用户订单金额:" + orderInfo.getOrderMoney());
        if (parOrder.getOrderMoney().compareTo(orderInfo.getOrderMoney()) < 0) {
          logger.info("===上级金额<用户金额===");
          logger.info("===使用上级金额进行分红===");
          logger.info("上级订单收益金额 ：" + parOrder.getMatflowPrice());
          分红金额 = parOrder.getMatflowPrice().multiply(默认奖励比例);
        } else {
          logger.info("订单收益金额:" + sendMoney);
          分红金额 = sendMoney.multiply(默认奖励比例);
        }

        logger.info("===该上级(" + b.getUserParLevle() + "层用户)可得分红:" + 分红金额);

        // 更新用户订单团队奖励
        userInfoService.updateBi(
            parUser.getId(),
            parUser.getId(),
            BiGetType.BI_GET_TYPE_20.getIndex(),
            BiType.BI_TYPE_500.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            分红金额,
            orderInfo.getId());

        // 增加业绩
        userInfoService.updateBi(
            parUser.getId(),
            parUser.getId(),
            BiGetType.BI_GET_TYPE_2.getIndex(),
            BiType.BI_TYPE_200.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            分红金额,
            orderInfo.getId());
      }
    }

    if (null != t.getMap().get("send_price")) {

      BigDecimal bonus = new BigDecimal(t.getMap().get("send_price").toString()); // 分红

      // 减少用户排单数
      UserInfo userInfo = new UserInfo();
      userInfo.setId(t.getAddUserId());
      userInfo.getMap().put("addUserOrderCount", 1);
      userInfoService.updateEntity(userInfo);

      // 发放订单分红
      userInfoService.updateBi(
          t.getAddUserId(),
          null,
          BiGetType.BI_GET_TYPE_1.getIndex(),
          BiType.BI_TYPE_300.getIndex(),
          BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
          bonus,
          t.getId());

      // 发放团队分红以及领导分红
      userInfoService.teamPrice(t.getAddUserId(), t.getId(), bonus);

      // 发放k5加权分红
      userInfoService.WeightingPrice(t.getAddUserId(), t.getId(), bonus);
    }
    return id;
  }

  public int removeEntity(OrderInfo t) {
    return this.orderInfoMapper.deleteEntity(t);
  }

  public List<OrderInfo> getEntityPaginatedList(OrderInfo t) {
    return this.orderInfoMapper.selectEntityPaginatedList(t);
  }
}
